import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:sprintf/sprintf.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/pages/devices/device_tab/components/detail_grid_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/battery_cell_tree/battery_cell_tree_model.dart';
import 'package:yt_devops/pages/devices/device_tab/model/device_item_model.dart';
import 'package:yt_devops/pages/devices/device_tab/utils/device_util.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/formats.dart';
import 'package:yt_devops/utils/self_develop_formats.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

import '../../../../../../utils/socket/use_socket.dart';
import 'bmu_bar_chart.dart';

class BatteryCellWidget extends StatefulWidget {
  final int productId;
  final BatteryCellTreeModel? cluster;

  const BatteryCellWidget(this.cluster, this.productId, {super.key});

  @override
  State<BatteryCellWidget> createState() => BatteryCellWidgetState();
}

class BatteryCellWidgetState extends State<BatteryCellWidget>
    with TickerProviderStateMixin {
  List<DetailItemModel> get statusItems => widget.productId ==
          ProductIDType.liquidEnergyBatteryStack.value
      ? [
          DetailItemModel(
              label: 'siteMonitor.runningState'.tr, //运行状态
              field: 'runState',
              format: Formates.closeFormat),
          DetailItemModel(
              label: ResKey.communication.tr, //通信
              field: 'connectStatus',
              format: (int? value) => $enumDecode(
                      $ConnectStatusTypeEnumMap, value,
                      unknownValue: ConnectStatusType.unConfig)
                  .label),
        ]
      : [
          DetailItemModel(
              label:
                  'PACK${'siteMonitor.fan'.tr}${'siteMonitor.stateFeedback'.tr}', //PACK风扇状态反馈

              field: 'packFanAlarmStatus',
              format: SelfDevelopFormate.pankFanAlarmFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU1']), // 'BMU1风扇'
              field: 'BMU1Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}1', //PACK风扇PWM占空比1
              field: 'PACKFPDC1',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU2']), // 'BMU2风扇'
              field: 'BMU2Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}2', //PACK风扇PWM占空比2
              field: 'PACKFPDC2',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU3']), // 'BMU3风扇'
              field: 'BMU3Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}3', //PACK风扇PWM占空比3
              field: 'PACKFPDC3',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU4']), // 'BMU4风扇'
              field: 'BMU4Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}4', //PACK风扇PWM占空比4
              field: 'PACKFPDC4',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU5']), // 'BMU5风扇'
              field: 'BMU5Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}5', //PACK风扇PWM占空比5
              field: 'PACKFPDC5',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU6']), // 'BMU6风扇'
              field: 'BMU6Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}6', //PACK风扇PWM占空比6
              field: 'PACKFPDC6',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU7']), // 'BMU7风扇'
              field: 'BMU7Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}7', //PACK风扇PWM占空比7
              field: 'PACKFPDC7',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU8']), // 'BMU8风扇'
              field: 'BMU8Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}8', //PACK风扇PWM占空比8
              field: 'PACKFPDC8',
              format: Formates.percentageFormat),
          DetailItemModel(
              label: sprintf(ResKey.deviceFanSentence.tr, ['BMU9']), // 'BMU9风扇'
              field: 'BMU9Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}9', //PACK风扇PWM占空比9
              field: 'PACKFPDC9',
              format: Formates.percentageFormat),
          DetailItemModel(
              label:
                  sprintf(ResKey.deviceFanSentence.tr, ['BMU10']), // 'BMU01风扇'
              field: 'BMU10Fan',
              format: Formates.openFormat),
          DetailItemModel(
              label: '${ResKey.devicePackFanPwm.tr}10', //PACK风扇PWM占空比10
              field: 'PACKFPDC10',
              format: Formates.percentageFormat),
        ];

  UseSubsribe subsribe = UseSubsribe();

  UseSubsribe connectSubsribe = UseSubsribe();

  StreamSubscription<Map<String, dynamic>>? connectSubscription;

  StreamSubscription<Map<String, dynamic>>? dataSubscription;

  Map<String, dynamic> dataSource = {};

  /// 电池单体tab
  List<BadgeTab>? tabs;

  late TabController tabController;
  // 控制更多弹窗控制器
  BrnCloseWindowController closeController = BrnCloseWindowController();

  //ListView 的 滚动控制器
  ScrollController scrollController = ScrollController();

  /// 请求方法
  late DeviceServices services;

  Map<int, DeviceModel>? bmuMap;

  int activBmuIndex = 0;
  @override
  void initState() {
    services = Get.put<DeviceServices>(DeviceServices());
    tabController = TabController(length: 10, vsync: this);
    tabs = List.generate(
        10,
        (index) => BadgeTab(
              text: 'BMU${index + 1}',
            ));
    tabController.addListener(() {
      activBmuIndex = tabController.index;
      if (mounted) {
        setState(() {});
      }
    });
    if (widget.cluster != null) {
      dataSubscription = subsribe
          .start([widget.cluster!.deviceId!], true)
          .stream
          .listen((event) {
            dealtData(event);
          });
      getBmus();
    }
    scrollController.addListener(() {
      closeController.closeMoreWindow();
    });
    super.initState();
  }

  @override
  void deactivate() {
    Log.d('deactivate');

    super.deactivate();
  }

  @override
  void didUpdateWidget(covariant BatteryCellWidget oldWidget) {
    if (widget.cluster != oldWidget.cluster) {
      if (oldWidget.cluster != null) {
        dataSubscription?.cancel();
        connectSubscription?.cancel();
        connectSubsribe.closeListen();
        subsribe.start([oldWidget.cluster!.deviceId!], false);
      }
      if (widget.cluster != null) {
        dataSubscription = subsribe
            .start([widget.cluster!.deviceId!], true)
            .stream
            .listen((event) {
              dealtData(event);
            });
        connectSubscription = connectSubsribe
            .start([widget.cluster!.deviceId!], true,
                type: MessageEventType.networkStatus)
            .stream
            .asBroadcastStream()
            .listen((data) {
              dealtData({}
                ..putIfAbsent('connectStatus', () => data['networkStatus']));
            });
        getBmus();
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  dealtData(Map<String, dynamic> event) {
    dataSource.addEntries(event.entries);
    setState(() {});
  }

  @override
  void dispose() async {
    tabController.dispose();
    scrollController.dispose();
    super.dispose();
    await dataSubscription?.cancel();
    await subsribe.closeListen();
    await connectSubscription?.cancel();
    await connectSubsribe.closeListen();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        closeController.closeMoreWindow();
        return true;
      },
      child: GestureDetector(
        onTap: () {
          closeController.closeMoreWindow();
        },
        child: ListView(
          controller: scrollController,
          shrinkWrap: true,
          padding: EdgeInsets.only(bottom: 10.h),
          children: [
            DeviceUtil.blockContainer(DetailGridWidget(
              title: ResKey.statusInfo.tr,
              items: statusItems,
              dataSource: dataSource,
              firsrtRowPercent: 0.65,
            )),
            DeviceUtil.blockContainer(Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                DeviceUtil.headTitle(
                    ResKey.deviceBatteryModuleIndividualInformation.tr),
              ],
            )),
            BrnTabBar(
              tabs: tabs,
              controller: tabController,
              tabWidth: 65.w,
              showMore: true,
              closeController: closeController,
              onTap: (state, index) => closeController.closeMoreWindow(),
            ),
            if (bmuMap != null)
              SizedBox(
                height: 330,
                child: TabBarView(
                  controller: tabController,
                  children: List.generate(
                      bmuMap?.keys.length ?? 0,
                      (index) => KeepAliveWrapper(BmuBarChart(
                          bmuMap![activBmuIndex + 1]!.deviceId!,
                          widget.productId))),
                ),
              ),
          ],
        ),
      ),
    );
  }

  getBmus() => Configs.httpClient.requestWithLoading(() async {
        var data = await services
            .getSubDevices({'parentId': widget.cluster!.deviceId});
        Map<int, DeviceModel> maps = {};

        for (var i = 0; i < data.length; i++) {
          maps.putIfAbsent(i + 1, () => DeviceModel.fromJson(data[i]));
        }
        tabs = List.generate(
            data.length,
            (index) => BadgeTab(
                  text: 'BMU${index + 1}',
                ));
        tabController = TabController(length: data.length, vsync: this);
        setState(() {
          bmuMap = maps;
        });
      });
}
